package chatComponents;

import java.io.*;
import java.net.*;
import java.util.ArrayList;

public class ChatServer{

	private int porta;
	private ArrayList<Cliente> clientes;
	private ServerSocket objServidor;
	private boolean chatFuncionando;
	
	public ChatServer(int porta){
		this.porta = porta;
		this.chatFuncionando = true;
		try
		{
			clientes = new ArrayList<Cliente>();
			this.objServidor = new ServerSocket(this.porta);
		}catch(Exception e){
			
		}
	}
	
	public void start(){
		if(this.chatFuncionando){
			Cliente objCliente = new  Cliente(this.objServidor);
			this.clientes.add(objCliente);
		
			Thread objThread = new Thread(objCliente);
		
			objThread.start();
		}
	}
	
	private class Cliente implements Runnable{
		ServerSocket objServer;
		boolean wantConnected;
			
		private Cliente(ServerSocket objServer){
			try{
				this.wantConnected = true;
				this.objServer = objServer;
			}catch(Exception e){
			
			}
		}

		@Override	
		public void run() {
			// TODO Auto-generated method stub
			try{
				Socket connectionSocket = this.objServer.accept();
				
				while(wantConnected){
					BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
					
					String received = inFromClient.readLine();
					
					System.out.println(received);
				}
				
				connectionSocket.close();
			}catch(Exception e){
				
			}
		}
	}
}
